package biz

import (
	"context"
	"manage/api/exam"
	"manage/internal/errors"
	"net/http"

	"github.com/gin-gonic/gin"
)

func (u *APIUseCase) Exam() *Method {
	remoteName := "考试"
	remoteExam := u.Repo.Exam

	return &Method{
		Get: func(c *gin.Context) {
			examID := c.Param("exam_id")

			remoteExam(func(ctx context.Context, esc exam.ExamServiceClient) {
				reply, err := esc.GetExam(ctx, &exam.GetExamRequest{
					ExamId: examID,
				})
				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
						Data: reply.ExamInfo,
					})
				}
			})
		},

		Post: func(c *gin.Context) {
			examName := c.PostForm("exam_name")
			examContent := c.PostForm("exam_content")
			examTime := c.PostForm("exam_time")
			teacherId := c.PostForm("teacher_id")

			remoteExam(func(ctx context.Context, esc exam.ExamServiceClient) {
				reply, err := esc.CreateExam(ctx, &exam.CreateExamRequest{
					ExamName:    examName,
					ExamContent: examContent,
					ExamTime:    examTime,
					TeacherId:   teacherId,
				})

				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
						Data: reply.ExamId,
					})
				}
			})
		},

		Put: func(c *gin.Context) {
			examID := c.Param("exam_id")
			examContent := c.PostForm("exam_content")
			examTime := c.PostForm("exam_time")
			teacherId := c.PostForm("teacher_id")

			remoteExam(func(ctx context.Context, esc exam.ExamServiceClient) {
				reply, err := esc.UpdateExam(ctx, &exam.UpdateExamRequest{
					ExamId:      examID,
					ExamContent: examContent,
					ExamTime:    examTime,
					TeacherId:   teacherId,
				})

				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
					})
				}
			})
		},

		Delete: func(c *gin.Context) {
			examId := c.Param("exam_id")

			remoteExam(func(ctx context.Context, esc exam.ExamServiceClient) {
				reply, err := esc.DeleteExam(ctx, &exam.DeleteExamRequest{
					ExamId: examId,
				})

				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
					})
				}
			})
		},
	}
}
